import { render, Element, setAttribute } from './element.js';

let allPatches,index = 0;
function patch (node,patches) {
  allPatches = patches;
  // 给某个元素打补丁
  recursion(node);
  // 默认从0个开始补丁
  console.log('index',index);
  Object.keys(patches).forEach((i)=>{
    if(parseInt(i)>index-1){
      console.log('patches[i]',i,patches[i]);
    }
  })
return node;
}

/**
 * 后序深度,找到最后一个孩子,查看是否有补丁,如果有打上
 * @para m node 在打补丁之前的真实节点
 */
function recursion(node){
  let currentPatch = allPatches[index++];
  let childNodes = node.childNodes;
  childNodes.forEach(child=>{
    recursion(child)
  });
  if (currentPatch&&currentPatch.length>0){
    doPatch(node,currentPatch);
  }
}



/**
 * 打补丁
 * @param node
 * @param patches
 */
function doPatch (node,patches) {
  patches.forEach(patch=>{
    switch (patch.type) {
      case 'ATTRS':
        for (let key in patch.attrs){
          let value = patch.attrs[key];
          if(value){
            setAttribute(node,key,value);
          }else{
              node.removeAttribute(key)
          }
        }
        break;
      case 'TEXT':
        node.textContent = patch.text;
        break;
      case 'REPLACE':
        let newNode = patch.newNode instanceof Element?render(patch.newNode) :document.createTextNode(patch.newNode);
        node.parentNode.replaceChild(newNode,node);
        break;
      case 'REMOVE':
        node.parentNode.removeChild(node);
        break;
      case 'CREATE':
        let createNode = patch.newNode instanceof Element?render(patch.newNode) :document.createTextNode(patch.newNode);
        node.parentNode.appendChild(createNode);
        break;
      default:
        break;
    }
  })
}

export default patch;